//
//  ReusableCellProtocol.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/6.
//
import UIKit

// MARK: - 事件类型枚举
enum CellEvent {
    case didSelect
    case buttonTapped(tag: Int, data: Any?)
    case switchChanged(isOn: Bool)
    case custom(String, [String: Any]?)
}

// MARK: - ReusableCell 协议
protocol ReusableCell: AnyObject {
    static var reuseIdentifier: String { get }
    static var nib: UINib { get }
    func configure(with data: Any)
    var eventHandler: ((CellEvent, Self) -> Void)? { get set }
}

extension ReusableCell {
    static var reuseIdentifier: String {
        return String(describing: self)
    }

    static var nib: UINib {
        return UINib(nibName: reuseIdentifier, bundle: nil)
    }
}

// MARK: - BaseTableViewCell 基类
class BaseTableViewCell: UITableViewCell, ReusableCell {
    var eventHandler: ((CellEvent, BaseTableViewCell) -> Void)?

    func configure(with data: Any) {
        // 公共配置逻辑
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        updateSelectionBackground(selected: selected)
    }

    private func updateSelectionBackground(selected: Bool) {
        if selected {
            // 选中状态背景，这里可以设置渐变颜色
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = [UIColor.lightGray.cgColor, UIColor.darkGray.cgColor]
            gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
            gradientLayer.frame = bounds
            gradientLayer.cornerRadius = 8
            selectedBackgroundView = UIView()
            selectedBackgroundView?.layer.insertSublayer(gradientLayer, at: 0)
        } else {
            selectedBackgroundView = nil
        }
    }
}

// MARK: - BaseCollectionViewCell 基类
class BaseCollectionViewCell: UICollectionViewCell, ReusableCell {
    var eventHandler: ((CellEvent, BaseCollectionViewCell) -> Void)?

    func configure(with data: Any) {
        // 公共配置逻辑
    }

    override var isSelected: Bool {
        didSet {
            updateSelectionBackground(selected: isSelected)
        }
    }

    private func updateSelectionBackground(selected: Bool) {
        if selected {
            // 选中状态背景，这里可以设置渐变颜色
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = [UIColor.lightGray.cgColor, UIColor.darkGray.cgColor]
            gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
            gradientLayer.frame = bounds
            gradientLayer.cornerRadius = 8
            contentView.layer.insertSublayer(gradientLayer, at: 0)
        } else {
            contentView.layer.sublayers?.forEach { layer in
                if layer is CAGradientLayer {
                    layer.removeFromSuperlayer()
                }
            }
        }
    }
}

// MARK: - TableViewManager 类
class TableViewManager: NSObject, UITableViewDataSource, UITableViewDelegate {
    private weak var tableView: UITableView?
    private var dataSource: [Any]
    private var cellType: BaseTableViewCell.Type
    private var didSelectRow: ((IndexPath) -> Void)?

    init(tableView: UITableView, dataSource: [Any], cellType: BaseTableViewCell.Type, didSelectRow: ((IndexPath) -> Void)? = nil) {
        self.tableView = tableView
        self.dataSource = dataSource
        self.cellType = cellType
        self.didSelectRow = didSelectRow
        super.init()

        setupTableView()
    }

    private func setupTableView() {
        guard let tableView = tableView else { return }
        tableView.dataSource = self
        tableView.delegate = self
        if let _ = Bundle.main.path(forResource: cellType.reuseIdentifier, ofType: "nib") {
            tableView.register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier)
        } else {
            tableView.register(cellType, forCellReuseIdentifier: cellType.reuseIdentifier)
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let tableView = self.tableView else {
            fatalError("TableView is nil")
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as! BaseTableViewCell
        let data = dataSource[indexPath.row]
        cell.configure(with: data)
        cell.eventHandler = { [weak self] event, cell in
            switch event {
            case .didSelect:
                self?.didSelectRow?(indexPath)
            default:
                break
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        didSelectRow?(indexPath)
    }
}

// MARK: - CollectionViewManager 类
class CollectionViewManager: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
    private weak var collectionView: UICollectionView?
    private var dataSource: [Any]
    private var cellType: BaseCollectionViewCell.Type
    private var didSelectItem: ((IndexPath) -> Void)?

    init(collectionView: UICollectionView, dataSource: [Any], cellType: BaseCollectionViewCell.Type, didSelectItem: ((IndexPath) -> Void)? = nil) {
        self.collectionView = collectionView
        self.dataSource = dataSource
        self.cellType = cellType
        self.didSelectItem = didSelectItem
        super.init()

        setupCollectionView()
    }

    private func setupCollectionView() {
        guard let collectionView = collectionView else { return }
        collectionView.dataSource = self
        collectionView.delegate = self
        if let _ = Bundle.main.path(forResource: cellType.reuseIdentifier, ofType: "nib") {
            collectionView.register(cellType.nib, forCellWithReuseIdentifier: cellType.reuseIdentifier)
        } else {
            collectionView.register(cellType, forCellWithReuseIdentifier: cellType.reuseIdentifier)
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let collectionView = self.collectionView else {
            fatalError("CollectionView is nil")
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath) as! BaseCollectionViewCell
        let data = dataSource[indexPath.item]
        cell.configure(with: data)
        cell.eventHandler = { [weak self] event, cell in
            switch event {
            case .didSelect:
                self?.didSelectItem?(indexPath)
            default:
                break
            }
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        didSelectItem?(indexPath)
    }
}

// MARK: - 自定义 TableViewCell
class CustomTableViewCell: BaseTableViewCell {
    @IBOutlet weak var titleLabel: UILabel!

    override func configure(with data: Any) {
        if let title = data as? String {
            titleLabel.text = title
        }
        let button = UIButton(type: .system)
        button.setTitle("Click me", for: .normal)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        contentView.addSubview(button)
        button.frame = CGRect(x: 10, y: 10, width: 100, height: 30)
    }

    @objc private func buttonTapped() {
        eventHandler?(.buttonTapped(tag: 1, data: nil), self)
    }
}

// MARK: - 自定义 CollectionViewCell
class CustomCollectionViewCell: BaseCollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!

    override func configure(with data: Any) {
        if let title = data as? String {
            titleLabel.text = title
        }
        let button = UIButton(type: .system)
        button.setTitle("Click me", for: .normal)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        contentView.addSubview(button)
        button.frame = CGRect(x: 10, y: 10, width: 100, height: 30)
    }

    @objc private func buttonTapped() {
        eventHandler?(.buttonTapped(tag: 1, data: nil), self)
    }
}

// MARK: - 视图控制器
class KLMViewController: UIViewController {
    private let tableView = UITableView()
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        return UICollectionView(frame: .zero, collectionViewLayout: layout)
    }()
    private let tableViewData = ["Table Item 1", "Table Item 2", "Table Item 3"]
    private let collectionViewData = ["Collection Item 1", "Collection Item 2", "Collection Item 3"]
    private var tableViewManager: TableViewManager?
    private var collectionViewManager: CollectionViewManager?

    override func viewDidLoad() {
        super.viewDidLoad()

        // 配置 TableView
        tableView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 200)
        view.addSubview(tableView)
        tableViewManager = TableViewManager(tableView: tableView, dataSource: tableViewData, cellType: CustomTableViewCell.self) { [weak self] indexPath in
            print("TableView did select row at \(indexPath)")
        }

        // 配置 CollectionView
        collectionView.frame = CGRect(x: 0, y: 250, width: view.bounds.width, height: 200)
        view.addSubview(collectionView)
        collectionViewManager = CollectionViewManager(collectionView: collectionView, dataSource: collectionViewData, cellType: CustomCollectionViewCell.self) { [weak self] indexPath in
            print("CollectionView did select item at \(indexPath)")
        }
    }
}
